package com.streamkar.rest;

import com.alibaba.fastjson.JSONArray;
import com.streamkar.common.config.session.UserSession;
import com.streamkar.constant.Constants;
import com.streamkar.constant.ReturnCode;
import com.streamkar.entity.base.Response;
import com.streamkar.entity.base.ResponseData;
import com.streamkar.entity.domain.Agency;
import com.streamkar.entity.domain.Talent;
import com.streamkar.entity.request.AgencyRequest;
import com.streamkar.entity.request.TalentRequest;
import com.streamkar.service.AgencyService;
import com.streamkar.service.TalentService;
import com.streamkar.util.EsUtil;
import com.streamkar.util.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @ClassName AdminRest
 * @Description
 * @Author tyfrost
 * @Date 2018/11/13 下午11:50
 * @Version 1.0
 */
@RestController
public class AdminRest {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdminRest.class);

    @Autowired
    TalentService talentService;

    @Autowired
    AgencyService agencyService;

    @Autowired
    EsUtil esUtil;

    @Autowired
    UserSession userSession;

    @Autowired
    Environment environment;

    @Autowired
    FileUtil fileUtil;

    @RequestMapping(value = "/admin/home", method = RequestMethod.GET)
    @ResponseBody
    public Response agencyStat() {
        ResponseData<JSONArray> response = new ResponseData<>();
        response.setData(agencyService.agencyHome());
        return response;
    }

    /**
     * 查询代理列表，只有talentmanager角色才可以操作
     *
     * @param agencyRequest 代理请求对象
     * @return
     */
    @RequestMapping(value = "/admin/agency/list", method = RequestMethod.GET)
    @ResponseBody
    public Response agencyList(AgencyRequest agencyRequest) {
        ResponseData<Object> response = new ResponseData<>();
        response.setData(agencyService.agencyList(agencyRequest.toEvent(), agencyRequest.getQueryValue()));
        return response;
    }

    @RequestMapping(value = "/admin/talent/list", method = RequestMethod.GET)
    @ResponseBody
    public Response talentList(TalentRequest talentRequest) {
        ResponseData<Object> response = new ResponseData<>();

        // 主播等级 1:红星主播 1-6 2：钻石主播 7-11 3：皇冠 12-55
        Integer talentLevel = talentRequest.getTalentLevel();
        int startLevel = Constants.START_LEVEL;
        int endLevel = Constants.END_LEVEL;
        if (Objects.equals(talentLevel, new Integer(1))) {
            endLevel = 6;
        } else if (Objects.equals(talentLevel, new Integer(2))) {
            startLevel = 7;
            endLevel = 11;
        } else if (Objects.equals(talentLevel, new Integer(3))) {
            startLevel = 12;
        }
        response.setData(talentService.talentList(talentRequest.toEvent(), startLevel, endLevel, talentRequest.getQueryValue()));
        return response;
    }

    @RequestMapping(value = "/admin/agency/{agencyId}", method = RequestMethod.GET)
    @ResponseBody
    public Response agencyDetail(@PathVariable(value = "agencyId") final Integer agencyId) {
        ResponseData<Agency> response = new ResponseData<>();

        // 查询
        Agency agency = agencyService.agencyInfo(agencyId);

        // 代理不为空不为空则继续代理统计信息
        if (null != agency) {
            JSONArray agencyStat = agencyService.agencyStat(agency.getAgencyId());
            if (!CollectionUtils.isEmpty(agencyStat)) {
                agency.setAgencyStat(agencyStat);
            }
        }
        response.setData(agency);
        return response;
    }

    @RequestMapping(value = "/admin/talent/{talentId}", method = RequestMethod.GET)
    @ResponseBody
    public Response talentDetail(@PathVariable(value = "talentId") final Integer talentId) {
        ResponseData<Talent> response = new ResponseData<>();
        // 查询主播
        Talent talent = talentService.talentInfo(talentId);

        // 主播不为空则继续查询家族
        if (null != talent) {
            Agency agency = agencyService.agencyInfo(talent.getAgencyId());
            if (null != agency) {
                talent.setAgency(agency);
            }
        }
        response.setData(talent);
        return response;
    }

    @RequestMapping(value = "/admin/talent/stat/{talentId}", method = RequestMethod.GET)
    @ResponseBody
    public Response talentStat(@PathVariable(value = "talentId") final Integer talentId) {
        ResponseData<Object> response = new ResponseData<>();
        response.setData(talentService.talentUserStat(talentId));
        return response;
    }

    @PutMapping("/admin/img/upload")
    public Response uploadImg(@RequestParam("fileImg") MultipartFile multipartFile, HttpServletRequest request) {
        ResponseData<String> response = new ResponseData();
        if (multipartFile.isEmpty() || StringUtils.isBlank(multipartFile.getOriginalFilename())) {
            response.setCode(ReturnCode.FILE_UPLOAD_ERROR);
            return response;
        }
        String contentType = multipartFile.getContentType();
        if (!contentType.contains("")) {
            response.setCode(ReturnCode.BAD_FILE);
            return response;
        }
        String originalFilename = multipartFile.getOriginalFilename();
        //处理图片
        Integer userId = userSession.getUserId();
        String accessPath = environment.getProperty("access.url");
        try {
            accessPath = fileUtil.saveImg(multipartFile, userId, environment.getProperty("img.path"), accessPath);
            if (StringUtils.isNotBlank(accessPath)) {
                response.setData(accessPath);
            }
            LOGGER.info("上传图片:name={},type={},filePath={}", originalFilename, contentType, accessPath);
            return response;
        } catch (Exception e) {
            LOGGER.error("上传图片:name={},type={} catch an exception", originalFilename, contentType, e);
            response.setCode(ReturnCode.FILE_UPLOAD_ERROR);
            return response;
        }
    }
}
